import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import db from '../database/db';

export interface Competitor {
  id: string;
  username: string;
  nickname: string;
  avatar: string;
  followers: number;
  following: number;
  posts: number;
  likes: number;
  comments: number;
  shares: number;
  engagementRate: number;
  category: string;
  lastUpdated: string;
  status: 'tracking' | 'paused';
  createdAt: string;
}

interface CompetitorState {
  competitors: Competitor[];
  loading: boolean;
  error: string | null;
  
  // Actions
  fetchCompetitors: () => Promise<void>;
  addCompetitor: (competitor: Omit<Competitor, 'id' | 'createdAt'>) => Promise<void>;
  updateCompetitor: (id: string, updates: Partial<Competitor>) => Promise<void>;
  deleteCompetitor: (id: string) => Promise<void>;
  getCompetitorsByCategory: (category: string) => Competitor[];
  getCompetitorsByStatus: (status: Competitor['status']) => Competitor[];
}

export const useCompetitorStore = create<CompetitorState>()(
  devtools(
    (set, get) => ({
      competitors: [],
      loading: false,
      error: null,

      fetchCompetitors: async () => {
        set({ loading: true, error: null });
        try {
          const stmt = db.prepare('SELECT * FROM competitors ORDER BY createdAt DESC');
          const competitors = stmt.all() as Competitor[];
          set({ competitors, loading: false });
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      addCompetitor: async (competitor) => {
        set({ loading: true, error: null });
        try {
          const id = Date.now().toString();
          const now = new Date().toISOString();
          const newCompetitor: Competitor = {
            ...competitor,
            id,
            createdAt: now,
          };

          const stmt = db.prepare(`
            INSERT INTO competitors (id, username, nickname, avatar, followers, following, posts, likes, comments, shares, engagementRate, category, lastUpdated, status, createdAt)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
          `);
          stmt.run(
            newCompetitor.id,
            newCompetitor.username,
            newCompetitor.nickname,
            newCompetitor.avatar,
            newCompetitor.followers,
            newCompetitor.following,
            newCompetitor.posts,
            newCompetitor.likes,
            newCompetitor.comments,
            newCompetitor.shares,
            newCompetitor.engagementRate,
            newCompetitor.category,
            newCompetitor.lastUpdated,
            newCompetitor.status,
            newCompetitor.createdAt
          );

          set(state => ({
            competitors: [newCompetitor, ...state.competitors],
            loading: false
          }));
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      updateCompetitor: async (id, updates) => {
        set({ loading: true, error: null });
        try {
          const updateFields = Object.keys(updates)
            .filter(key => key !== 'id')
            .map(key => `${key} = ?`)
            .join(', ');

          const stmt = db.prepare(`
            UPDATE competitors 
            SET ${updateFields}
            WHERE id = ?
          `);

          const values = [...Object.values(updates), id];
          stmt.run(...values);

          set(state => ({
            competitors: state.competitors.map(competitor =>
              competitor.id === id ? { ...competitor, ...updates } : competitor
            ),
            loading: false
          }));
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      deleteCompetitor: async (id) => {
        set({ loading: true, error: null });
        try {
          const stmt = db.prepare('DELETE FROM competitors WHERE id = ?');
          stmt.run(id);

          set(state => ({
            competitors: state.competitors.filter(competitor => competitor.id !== id),
            loading: false
          }));
        } catch (error) {
          set({ error: (error as Error).message, loading: false });
        }
      },

      getCompetitorsByCategory: (category) => {
        return get().competitors.filter(competitor => competitor.category === category);
      },

      getCompetitorsByStatus: (status) => {
        return get().competitors.filter(competitor => competitor.status === status);
      },
    }),
    {
      name: 'competitor-store',
    }
  )
); 